//
//  GCDTimer.m
//  Tools
//
//  Created by han on 2019/1/4.
//  Copyright © 2019 han. All rights reserved.
//

#import "GCDTimer.h"
@interface GCDTimer()
@property (nonatomic, strong) dispatch_source_t timerSource;
@property (nonatomic, strong) void (^triggerBlock)(void);
@property (nonatomic, assign) BOOL repeats;
@property (nonatomic, assign) NSTimeInterval interval;
@end
@implementation GCDTimer
- (instancetype)initWithInterval:(NSTimeInterval)interval repeats:(BOOL)repeats triggerBlock:(void (^)(void))triggerBlock{
    if (self = [super init]) {
        self.triggerBlock = triggerBlock;
        self.repeats = repeats;
        self.interval = interval;
        [self setupTimer];
    }
    return self;
}
- (void)setupTimer{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    uint64_t timerInterval = self.interval * NSEC_PER_SEC;
    if (!self.repeats) {
        timerInterval = DISPATCH_TIME_FOREVER;
    }
    //设置定时器：立即执行；延时1s:dispatch_walltime(NULL, 1* NSEC_PER_SEC)
    dispatch_source_set_timer(self.timerSource, dispatch_walltime(NULL, 0), timerInterval, 0.f);
    __weak __typeof(self) weakSelf = self;
    dispatch_source_set_event_handler(self.timerSource, ^{
        [weakSelf sendTriggerEvent];
    });
}
- (void)sendTriggerEvent{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.triggerBlock) {
            self.triggerBlock();
        }
    });
}
//重新开始
- (void)resume{
    dispatch_resume(self.timerSource);
}
//延时
- (void)suspend{
    dispatch_source_cancel(self.timerSource);
    [self setupTimer];
}
- (void)stop{
    if (_timerSource) {
        dispatch_source_cancel(_timerSource);
        _timerSource = nil;
    }
}
@end
